﻿using System;
using System.IO;
using System.Net;
using iPhOwa.Exchange.Managers;

namespace iPhOwa.Web
{
	/// <summary>
	/// Get an attachment.
	/// </summary>
	public partial class ViewAttachment : iPhOwaPage
	{
		private const int Size16K = 16384;

		/// <summary>
		/// Page load event.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected void Page_Load(object sender, EventArgs e)
		{
			WebResponse response = MessageManager.GetAttachment(Path, OwaSession);

			Response.ContentType = response.ContentType;
			Response.AddHeader("content-disposition", string.Concat("attachment; filename=", System.IO.Path.GetFileName(Path.LocalPath)));

			var contents = new byte[response.ContentLength];

			// HACK: When using SSL connections with GetResponseStream you can only read 16K at a time.
			using(Stream stream = response.GetResponseStream())
			{
				int offset = 0;
				int read;
				var toRead = (int)response.ContentLength;
				int count = (Size16K < toRead) ? Size16K : toRead;

				while((read = stream.Read(contents, offset, count)) > 0)
				{
					toRead -= read;
					offset += read;

					count = (Size16K < toRead) ? Size16K : toRead;
				}
			}

			Response.BinaryWrite(contents);
			Response.End();
		}
	}
}